package com.duan.dao.user;

import com.duan.dao.baseDao;
import com.duan.pojo.Role;
import com.duan.pojo.User;
import com.mysql.jdbc.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserDaoImpl implements UserDao{

    public  User loginDao(Connection connection, String userCode) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet  resultSet = null;
        User user = null;

        if(connection != null){
            String sql = "select * from smbms_user where userCode = ?";
            Object []params = {userCode};
            resultSet = baseDao.execute(connection, sql, params, resultSet, preparedStatement);


            if(resultSet.next()){
                System.out.println("==================================查到有人");
                user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUserCode(resultSet.getString("userCode"));
                user.setUserName(resultSet.getString("userName"));
                user.setUserPassword(resultSet.getString("userPassword"));
                user.setGender(resultSet.getInt("gender"));
                user.setAddress(resultSet.getString("address"));
                user.setBirthday(resultSet.getDate("birthday"));
                user.setCreatedBy(resultSet.getInt("createdBy"));
                user.setPhone(resultSet.getString("phone"));
                user.setUserRole(resultSet.getInt("userRole"));
                user.setCreationDate(resultSet.getTimestamp("creationDate"));
                user.setModifyBy(resultSet.getInt("modifyBy"));
                user.setModifyDate(resultSet.getTimestamp("modifyDate"));
            }
            baseDao.closeResource(null, preparedStatement, resultSet);

        }
        return user;
    }

    public int updatePwd(Connection connection, int id, String password) throws SQLException {
        PreparedStatement preparedStatement = null;
        String sql = null;
        int res = 0;

        if(connection != null){
            sql = "update smbms_user set userPassword = ? where id = ?";
            Object[] params = {password, id};
            res = baseDao.execute(connection, sql, params, preparedStatement);
            baseDao.closeResource(null, preparedStatement, null);
        }
        return res;
    }

    //根据用户名或者角色查询用户总数【尊哪里接的sql】

    public int numOfUser(Connection connection, String userName, int userRole) throws SQLException {

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        int count = 0;

        if(connection != null){
            //1. 联表查询：查询 用户表中的userRole 等于 角色表中的角色id时 的所有行数！（因为页面列表中用户信息要显示用户角色名字）
            //"select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id";
            StringBuilder sql = new StringBuilder();
            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");

            ArrayList<Object> list = new ArrayList<Object>();//存放我们的参数

            //2. 查询条件1：用户名
            if(!StringUtils.isNullOrEmpty(userName)){ //如过界面中输入了userName，则往SQL中加入新的查询条件,进行模糊查询
                sql.append(" and u.userName like ?");
                list.add("%" + userName + "%"); //index=0
            }

            //3. 查询条件2：用户角色
            if(userRole > 0){
                sql.append(" and u.userRole = ?");
                list.add(userRole); //index=1
            }

            //输出完整的SQL
            System.out.println("UserDaoImpl -> numOfUser : " + sql.toString());
            //怎么把list转换为数组
            Object[] params = list.toArray();

            resultSet = baseDao.execute(connection, sql.toString(), params, resultSet, preparedStatement);

            //resultSet输出的结果是指定查询信息的用户数量
            if(resultSet.next()){
                count = resultSet.getInt("count");//从结果集中获取最终的数量
            }

            baseDao.closeResource(null, preparedStatement, resultSet);
        }

        return count;
    }

    //获取指定条件下的用户列表
    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<User> userList = new ArrayList<User>();

        if(connection != null){
            connection = baseDao.getConnection();

            StringBuilder sql = new StringBuilder();
            sql.append("select * from smbms_user u, smbms_role r where u.userRole = r.id");
            ArrayList<Object> list = new ArrayList<Object>();//收集有用指定的sql条件查询参数

            //条件1： 指定用户名
            if(!StringUtils.isNullOrEmpty(userName)){
                sql.append(" and u.userName like ?");
                list.add("%" + userName + "%");//通配符
            }

            //条件2： 指定用户角色
            if(userRole > 0){
                sql.append(" and userRole = ?");
                list.add(userRole);
            }

            //条件3： 指定分页
            sql.append(" order by u.creationDate DESC limit ?,?");//DESC：降序
            //因为limit带2个值时：第一个数是开始位置，第二个数是要检索的行数（SQL中检索出来的第一行为行0，而不是行1）
            //输入的currenPageNo--------->页数
            //(currentPageNo - 1) * pageSize 后，currenPageNo等于页数对应表中的起始位置（行）
            currentPageNo = (currentPageNo - 1) * pageSize;
            list.add(currentPageNo); //要开始检索的位置
            list.add(pageSize); //从上述位置开始检索所少个

            System.out.println("sql ----- >" + sql.toString());//打印出来看看

            Object[] params = list.toArray();

            resultSet = baseDao.execute(connection, sql.toString(), params, resultSet, preparedStatement);
            while (resultSet.next()){
                User user1 = new User();
                user1.setId(resultSet.getInt("id"));
                user1.setUserCode(resultSet.getString("userCode"));
                user1.setUserName(resultSet.getString("userName"));
                user1.setGender(resultSet.getInt("gender"));
                user1.setBirthday(resultSet.getDate("birthday"));
                user1.setUserRole(resultSet.getInt("userRole"));
                user1.setUserRoleName(resultSet.getString("roleName"));
                user1.setPhone(resultSet.getString("phone"));

                userList.add(user1);
            }

            baseDao.closeResource(null, preparedStatement, resultSet);
        }

        return userList;
    }

    //增加用户
    public int insertUser(Connection connection, User user) throws SQLException {
        PreparedStatement preparedStatement = null;
        int res = 0;

        if(connection != null && user != null){
            String sql = "insert into smbms_user (userCode, userName, userPassword, gender, birthday, phone, address, userRole, creationDate, createdBy) values(?,?,?,?,?,?,?,?,?,?)";
            String userCode = user.getUserCode();
            String userName = user.getUserName();
            String userPassword = user.getUserPassword();
            int gender = user.getGender();
            Date birthday = user.getBirthday();
            String phone = user.getPhone();
            String address = user.getAddress();
            int userRole = user.getUserRole();
            Date creationDate = user.getCreationDate();
            Integer createdBy = user.getCreatedBy();

            Object []params = {userCode, userName, userPassword, gender, birthday, phone, address, userRole, creationDate, createdBy};

            res = baseDao.execute(connection, sql, params, preparedStatement);

            baseDao.closeResource(null, preparedStatement, null);
        }

        return res;
    }

    //查询存在此userCode的用户
    public User selectUserCodeExist(Connection connection, String userCode) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet res = null;
        User user = null;

        if(connection != null){
            String sql = "select * from smbms_user where userCode = ?";
            Object [] params = {userCode};

            res = baseDao.execute(connection, sql, params, res, preparedStatement);

            if(res.next()){
                user = new User();
                user.setId(res.getInt("id"));
                user.setUserCode(res.getString("userCode"));
                user.setUserName(res.getString("userName"));
                user.setGender(res.getInt("gender"));
                user.setBirthday(res.getDate("birthday"));
                user.setUserRole(res.getInt("userRole"));
                user.setUserRoleName(res.getString("roleName"));
                user.setPhone(res.getString("phone"));
            }

            baseDao.closeResource(null, preparedStatement, res);
        }

        return user;
    }

    //删除用户
    public int deleteUser(Connection connection, int userid) throws SQLException {
        PreparedStatement preparedStatement = null;
        int res = 0;
        if(connection != null){
            String sql = "delete from smbms_user where id = ?";
            Object[] params = {userid};
            res = baseDao.execute(connection, sql, params, preparedStatement);

            baseDao.closeResource(null, preparedStatement, null);
        }
        return res;
    }

    //获取指定id用户信息
    public User selectUserByid(Connection connection, int id) throws SQLException {
        User user = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if(null != connection){
            String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";
            Object[] params = {id};
            rs = baseDao.execute(connection, sql, params,rs, pstm);
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
                user.setUserRoleName(rs.getString("userRoleName"));
            }
            baseDao.closeResource(null, pstm, rs);
        }
        return user;
    }

    //修改

    public int modify(Connection connection, User user) throws Exception {
        // TODO Auto-generated method stub
        int flag = 0;
        PreparedStatement pstm = null;
        if(null != connection){
            String sql = "update smbms_user set userName=?,"+
                    "gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
            Object[] params = {user.getUserName(),user.getGender(),user.getBirthday(),
                    user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),
                    user.getModifyDate(),user.getId()};
            flag = baseDao.execute(connection, sql, params, pstm);
            baseDao.closeResource(null, pstm, null);
        }
        return flag;
    }


}
